package com.demoworld;

import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

/**
 * Created by li_wb on 2017/8/23.
 */
public class JsonUtils {
    private static final List<String> excludeFields = Arrays.asList("host", "pathname");
    private static Gson gson = GsonFactory.build(excludeFields, null, false);
    private static Gson prettyGson = GsonFactory.build(excludeFields, null, true);

    public static String toJson(Object obj) {
        String strJson = "";
        strJson = gson.toJson(obj);
        return strJson;
    }

    public static String toPrettyJson(Object obj) {
        return prettyGson.toJson(obj);
    }

    public static <T> T fromJson(String jsonString, Type type) {
        if (jsonString == null || jsonString.length() == 0) {
            return null;
        }
        T result = null;
        try {
            result = gson.fromJson(jsonString, type);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}
